package com.sdk.springbootwebsocketjavax.config;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
public class WebSocketController {

    @Autowired
    private WebSocket webSocket;

    @GetMapping("/send")
    public String sendWebSocketMessages() {
        try {
            // 创建业务消息信息
            JSONObject obj = new JSONObject();
            obj.put("cmd", "topic"); // 业务类型
            obj.put("msgId", UUID.randomUUID().toString()); // 消息id
            obj.put("msgTxt", UUID.randomUUID().toString()); // 消息内容

            // 全体发送
            webSocket.sendAllMessage(obj.toJSONString());

            // 单个用户发送 (userId为用户id)
            webSocket.sendOneMessage("1", obj.toJSONString());

            // 多个用户发送 (userIds为多个用户id，逗号‘,’分隔)
            webSocket.sendMoreMessage(new String[]{"1", "2"}, obj.toJSONString());

            return "消息发送成功";
        } catch (Exception e) {
            return "消息发送失败: " + e.getMessage();
        }
    }
}
